package com.android.meige.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.activity.BaseObject;
import com.android.meige.model.group.MainHeadNestSortData;
import com.android.meige.model.group.NewProductData;
import com.android.meige.model.group.NewProductDataCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.MyGridView;
import com.android.meige.view.group.VRefreshLayout;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/8/14.
 */

public class Fragment_NewProduct extends Fragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private View rootView;
    private AdaptListNewProduct adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private int page = 1;
    private View view;
    private MyGridView gridView1;
    private MyGridView gridView2;
    private ArrayList<MainHeadNestSortData> headNestSortDatas1 = new ArrayList<MainHeadNestSortData>();
    private ArrayList<MainHeadNestSortData> headNestSortDatas2 = new ArrayList<MainHeadNestSortData>();
    private ArrayList<NewProductData.DataBean.ListBean> listdata = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public Fragment_NewProduct() {

    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    private void initRecycle() {
        adapter = new AdaptListNewProduct(mcontext, listdata, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;

                }
                return false;
            }
        });
        initHeadSort();
    }

    private void initHeadSort() {
        /*头布局的加入*/
        View fragment_head = inflater.inflate(R.layout.new_product_head_banner, null, false);
        gridView1 = (MyGridView) fragment_head.findViewById(R.id.everybodybuy_gridview);
        gridView2 = (MyGridView) fragment_head.findViewById(R.id.choicetopic_gridview);
        adapter.addHeaderView(fragment_head);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        this.inflater = inflater;
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        mainTopTitle.setText("新品热拼");
        mainTopTitle.setTextColor(Color.parseColor("#ffffff"));
        mainTopBg.setBackgroundColor(Color.parseColor("#FF2741"));
        ReFreshData();
        initRecycle();
        return view;
    }

    private void ReFreshData() {
        GetListData(page);
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
                                GetListData(page);
                                mRefreshLayout.refreshComplete();
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }

    private class Adapt extends BaseAdapter {

        List<MainHeadNestSortData> listdata;
        int type;

        public Adapt(List<MainHeadNestSortData> listdata, int type) {
            this.listdata = listdata;
            this.type = type;
        }

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int pos, View convertView, ViewGroup parent) {
            View inflate_paystyle = LayoutInflater.from(mcontext).inflate(R.layout.newproduct_head_ivitem, null);
            ImageView typeicon = (ImageView) inflate_paystyle.findViewById(R.id.typeicon);
            if (listdata.get(pos).getDrawable() == 0) {
                ObjectUtils.photo(mcontext, listdata.get(pos).getThumb(), typeicon);
            } else {
                typeicon.setImageResource(listdata.get(pos).getDrawable());
            }
            switch (type) {
                case 1:
                    inflate_paystyle.findViewById(R.id.typell).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(mcontext, BaseObject.class);
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "热搜");
                            startActivity(intent);
                        }
                    });
                    break;
                case 2:
                    inflate_paystyle.findViewById(R.id.typell).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(mcontext, BaseObject.class);
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "精选专题");
                            startActivity(intent);
                        }
                    });
                    break;
            }
            return inflate_paystyle;
        }
    }

    public class AdaptListNewProduct extends BaseMultiItemQuickAdapter<NewProductData.DataBean.ListBean, BaseViewHolder> {

        public AdaptListNewProduct(Context context, ArrayList<NewProductData.DataBean.ListBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.item_list_disandsell);
        }

        @Override
        protected void convert(BaseViewHolder holder, NewProductData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    ((TextView) holder.getView(R.id.item_list_sort_aa_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(mContext, mainlistdata.getThumb(), ((ImageView) holder.getView(R.id.main_list_item_image)));
                    holder.setText(R.id.main_list_item_count, mainlistdata.getTeam_price() + "折");
                    holder.setText(R.id.main_list_item_tuannumber, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_start_soon_num, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_free_num, mainlistdata.getTeam_num() + "人团");
                    holder.setVisible(R.id.main_list_item_go_kai, true);
                    String sellNum = mainlistdata.getSell_num();
                    if (!TextUtils.isEmpty(sellNum) && !sellNum.equals("0")) {
                        holder.setText(R.id.main_list_item_alltuannumber2, "已团" + sellNum + "件");
                    }
                    holder.setText(R.id.main_list_item_title, mainlistdata.getName());
                    String price1 = mainlistdata.getTeam_price();
                    SpannableString msp = new SpannableString("￥" + price1);
                    msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.setText(R.id.main_list_item_money_after, msp);
                    break;
            }
        }
    }

    private void GetListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.NEW_PRODUCT;
            HashMap<String, String> map = new HashMap<>();
            map.put("page", page + "");
            HttpUtils.get(address, map, mCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    NewProductDataCallback mCallback = new NewProductDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(NewProductData response, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            NewProductData.DataBean data = response.getData();
            if (response.getCode() == 0 && data != null) {
                headNestSortDatas1.clear();
                headNestSortDatas2.clear();
                List<NewProductData.DataBean.UserBean> user1 = data.getUser1();
                if (ObjectUtils.listHasData(user1)) {
                    int limit1 = 2;
                    if (user1.size() < 2) {
                        limit1 = user1.size();
                    }
                    for (int i = 0; i < limit1; i++) {
                        headNestSortDatas1.add(new MainHeadNestSortData("", "", user1.get(i).getPhoto(), 0, ""));
                    }
                    headNestSortDatas1.add(new MainHeadNestSortData("", "查看全部", null, R.mipmap.main_sort_all, ""));
                    Adapt adapt1 = new Adapt(headNestSortDatas1, 1);
                    gridView1.setAdapter(adapt1);
                }

                List<NewProductData.DataBean.UserBean> user2 = data.getUser2();
                if (ObjectUtils.listHasData(user2)) {
                    int limit2 = 2;
                    if (user2.size() < 2) {
                        limit2 = user2.size();
                    }
                    for (int i = 0; i < limit2; i++) {
                        headNestSortDatas2.add(new MainHeadNestSortData("", "", user2.get(i).getPhoto(), 0, ""));
                    }
                    headNestSortDatas2.add(new MainHeadNestSortData("", "查看全部", null, R.mipmap.main_sort_all, ""));
                    Adapt adapt2 = new Adapt(headNestSortDatas2, 2);
                    gridView2.setAdapter(adapt2);
                }

                List<NewProductData.DataBean.ListBean> list = data.getList();
                if (ObjectUtils.listHasData(list)) {
                    if (page == 1) {
                        listdata.clear();
                        listdata.addAll(list);
                        adapter.setNewData(list);
                    } else {
                        listdata.addAll(list);
                        adapter.addData(list);
                        adapter.loadMoreComplete();
                    }
                } else {
                    adapter.loadMoreEnd();
                }
            } else {
                if (page == 1) {
                    noData.setVisibility(View.VISIBLE);
                } else {
                    adapter.loadMoreFail();
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            }
        }
    };
}
